package com.lanxin.zc.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.github.pagehelper.Page;
import com.lanxin.hr.entity.JcBasicdatavalue;
import com.lanxin.hr.entity.ZzAccount;
import com.lanxin.hr.entity.ZzEmployee;
import com.lanxin.hr.service.IJcBasicdatavalueService;
import com.lanxin.hr.service.IZzEmployeeService;
import com.lanxin.judge.Vo.NodeVo;
import com.lanxin.judge.entity.LcApproval;
import com.lanxin.judge.entity.LcFlow;
import com.lanxin.judge.service.ILcApprovalService;
import com.lanxin.judge.service.ILcFlowService;
import com.lanxin.judge.service.ILcNodeService;
import com.lanxin.zc.entity.*;
import com.lanxin.zc.service.IZcAssetService;
import com.lanxin.zc.service.IZcAssetmoveapplyService;
import com.lanxin.zc.service.IZcAssetmovedetailsService;
import com.lanxin.zc.vo.AllzcassetmoveapplyVo;
import com.lanxin.zc.vo.AllzcassetpurchaseapplyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 
 * @since 2025-07-16
 */
@Controller
@RequestMapping("/zc-assetmoveapply")
public class ZcAssetmoveapplyController {
    @Autowired
    private IZcAssetmoveapplyService zcAssetmoveapplyService;
    @Autowired
    private IZcAssetmovedetailsService zcAssetmovedetailsService;
    @Autowired
    private IZzEmployeeService zzEmployeeService;
    @Autowired
    private ILcFlowService lcFlowService;
    @Autowired
    private IJcBasicdatavalueService jcBasicdatavalueService;
    @Autowired
    private IZcAssetService zcAssetService;
    @Autowired
    private ILcApprovalService lcApprovalService;
    @Autowired
    private ILcNodeService lcNodeService;

    @RequestMapping("/tozcassetmoveapplylist")
    public ModelAndView tozcassetmoveapplylist(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
            @RequestParam(value = "docNo", required = false) String docNo,
            @RequestParam(value = "empName", required = false) String empName,
            @RequestParam(value = "submitDate", required = false) String submitDate,
            @RequestParam(value = "status", required = false) String status) {

        // 调用服务层获取分页数据
        Page<AllzcassetmoveapplyVo> allzcassetmoveapplyVos = zcAssetmoveapplyService.selectzcassetmoveList(page, pageSize, docNo, empName, submitDate, status);

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("zc/zcassetmoveapply/zcassetmoveapplylist");

        // 添加分页数据到视图
        modelAndView.addObject("allzcassetmoveapplyVos", allzcassetmoveapplyVos);
        modelAndView.addObject("docNo", docNo);
        modelAndView.addObject("empName", empName);
        modelAndView.addObject("submitDate", submitDate);
        modelAndView.addObject("status", status);

        // 添加分页信息（可选）
        modelAndView.addObject("total", allzcassetmoveapplyVos.getTotal());
        modelAndView.addObject("pageNum", allzcassetmoveapplyVos.getPageNum());
        modelAndView.addObject("pageSize", allzcassetmoveapplyVos.getPageSize());
        modelAndView.addObject("pages", allzcassetmoveapplyVos.getPages()); // 总页数

        return modelAndView;
    }

    @RequestMapping("/doAssetMove")
    public String doAssetMove(@RequestParam(required = false) Integer oid) {
        QueryWrapper<ZcAssetmovedetails> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parentid", oid);
        List<ZcAssetmovedetails> zcAssetmovedetailsList = zcAssetmovedetailsService.list(queryWrapper);
        for (ZcAssetmovedetails details : zcAssetmovedetailsList) {

            ZcAsset asset = zcAssetService.getById(details.getAssetId());
            asset.setDepositary(details.getTargetPlace());
            zcAssetService.updateById(asset);
        }
        ZcAssetmoveapply apply = zcAssetmoveapplyService.getById(oid);
        apply.setStatus("S");
        apply.setMoveDate(LocalDate.now());
        zcAssetmoveapplyService.updateById(apply);

        return "redirect:/zc-assetmoveapply/tozcassetmoveapplylist";
    }

    @RequestMapping("/tomyzcassetmoveapplylist")
    public ModelAndView tomyzcassetmoveapplylist(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
            @RequestParam(value = "docNo", required = false) String docNo,
            @RequestParam(value = "submitDate", required = false) String submitDate,
            @RequestParam(value = "status", required = false) String status, HttpSession session) {

        // 调用服务层获取分页数据
        ZzAccount myaccount = (ZzAccount) session.getAttribute("myaccount");
        QueryWrapper<ZzEmployee> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("oid", myaccount.getAid());
        ZzEmployee employee= zzEmployeeService.getOne(queryWrapper);
        Page<AllzcassetmoveapplyVo>  selectmyzcassetmoveList= zcAssetmoveapplyService.selectmyzcassetmoveList(page,pageSize,docNo,submitDate,status,employee.getOid());

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("zc/zcassetmoveapply/myzcassetmoveapplylist");

        // 添加分页数据到视图
        modelAndView.addObject("selectmyzcassetmoveList", selectmyzcassetmoveList);
        modelAndView.addObject("docNo", docNo);
        modelAndView.addObject("submitDate", submitDate);
        modelAndView.addObject("status", status);

        // 添加分页信息（可选）
        modelAndView.addObject("total", selectmyzcassetmoveList.getTotal());
        modelAndView.addObject("pageNum", selectmyzcassetmoveList.getPageNum());
        modelAndView.addObject("pageSize", selectmyzcassetmoveList.getPageSize());
        modelAndView.addObject("pages", selectmyzcassetmoveList.getPages()); // 总页数

        return modelAndView;
    }


    @RequestMapping("/toeditAssetmoveapply")
    public ModelAndView toeditAssetmoveapply(@RequestParam(required = false) Integer oid) {
        ModelAndView modelAndView = new ModelAndView();

        // 1. 查询基础数据
        // 流程列表
        QueryWrapper<LcFlow> LCqueryWrapper = new QueryWrapper<>();
        LCqueryWrapper.eq("state", "Y").eq("docType", "YDD");
        List<LcFlow> lcFlow = lcFlowService.list(LCqueryWrapper);
        modelAndView.addObject("lcFlow", lcFlow);

        // 移动事由(类型5)
        QueryWrapper<JcBasicdatavalue> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("state", "Y").eq("type", 5);
        List<JcBasicdatavalue> jcBasicdatavalues = jcBasicdatavalueService.list(queryWrapper);
        modelAndView.addObject("jcBasicdatavalues", jcBasicdatavalues);

        // 存放地点(类型2)
        QueryWrapper<JcBasicdatavalue> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("state", "Y").eq("type", 2);
        List<JcBasicdatavalue> jcBasicdatavalues2 = jcBasicdatavalueService.list(queryWrapper2);
        modelAndView.addObject("jcBasicdatavalues2", jcBasicdatavalues2);

        // 可用资产列表
        QueryWrapper<ZcAsset> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.ne("status", "N");
        List<ZcAsset> zcAssets = zcAssetService.list(queryWrapper1);
        modelAndView.addObject("zcAssets", zcAssets);

        // 2. 如果是编辑操作，查询主表和明细数据
        if (oid != null) {
            // 查询主表数据
            ZcAssetmoveapply apply = zcAssetmoveapplyService.getById(oid);
            modelAndView.addObject("zcAssetmoveapply", apply);

            // 查询申请人信息
            if (apply.getProposer() != null) {
                ZzEmployee proposer = zzEmployeeService.getById(apply.getProposer());
                modelAndView.addObject("empName", proposer.getEmpName());
            }

            // 查询明细数据
            QueryWrapper<ZcAssetmovedetails> detailsWrapper = new QueryWrapper<>();
            detailsWrapper.eq("parentid", oid);
            List<ZcAssetmovedetails> details = zcAssetmovedetailsService.list(detailsWrapper);

            // 为每个明细查询资产信息
            List<Map<String, Object>> detailList = new ArrayList<>();
            for (ZcAssetmovedetails detail : details) {
                Map<String, Object> detailMap = new HashMap<>();
                detailMap.put("detail", detail);

                // 查询资产信息
                if (detail.getAssetId() != null) {
                    ZcAsset asset = zcAssetService.getById(detail.getAssetId());
                    detailMap.put("asset", asset);

                    // 查询原保管人信息
                    if (asset.getKeeper() != null) {
                        ZzEmployee keeper = zzEmployeeService.getById(asset.getKeeper());
                        detailMap.put("keeper", keeper);
                    }

                    // 查询原存放地信息
                    if (asset.getDepositary() != null) {
                        JcBasicdatavalue storage = jcBasicdatavalueService.getById(asset.getDepositary());
                        detailMap.put("storage", storage);
                    }
                }
                detailList.add(detailMap);
            }
            modelAndView.addObject("details", detailList);
        }

        modelAndView.setViewName("zc/zcassetmoveapply/editAssetmoveapply");
        return modelAndView;
    }


    @RequestMapping("/editAssetmoveapply")
    public String editAssetmoveapply(
            @RequestParam(required = false) Integer oid,
            @RequestParam(value = "docNo", required = false) String docNo,
            @RequestParam(value = "flowid", required = false) Integer flowid,
            @RequestParam(value = "moveReason", required = false) Integer moveReason,
            @RequestParam(value = "remark", required = false) String remark,
            @RequestParam(value = "proposer", required = false) Integer proposer,
            @RequestParam(value = "empName", required = false) String empName,
            @RequestParam(value = "assetId", required = false) Integer[] assetIds,
            @RequestParam(value = "formPlace", required = false) Integer[] formPlaces,
            @RequestParam(value = "yuanRen", required = false) Integer[] yuanRens,
            @RequestParam(value = "targetPlace", required = false) Integer[] targetPlaces,
            @RequestParam(value = "moveDate", required = false) String[] moveDates,
            @RequestParam(value = "remarks", required = false) String[] detailsRemarks,
            HttpSession session) {


        // 获取当前登录用户信息
        ZzAccount myaccount = (ZzAccount) session.getAttribute("myaccount");
        if (myaccount == null) {
            return "redirect:/login";
        }

        // 判断是新增还是修改
        boolean isUpdate = oid != null;

        // 获取或创建申请单对象
        ZcAssetmoveapply zcAssetmoveapply = isUpdate ?
                zcAssetmoveapplyService.getById(oid) : new ZcAssetmoveapply();

        if (zcAssetmoveapply == null) {
            // 如果要修改的记录不存在，按新增处理
            zcAssetmoveapply = new ZcAssetmoveapply();
            isUpdate = false;
        }

        // 设置基本属性
        zcAssetmoveapply.setOid(oid);
        zcAssetmoveapply.setFlowid(flowid);
        zcAssetmoveapply.setMoveReason(moveReason);
        zcAssetmoveapply.setRemark(remark);

        // 设置创建者和申请者
        if (!isUpdate) {
            zcAssetmoveapply.setCreator(myaccount.getAid());
            zcAssetmoveapply.setCreateDate(LocalDateTime.now());
        }


        zcAssetmoveapply.setProposer(proposer);
        QueryWrapper<ZzEmployee> departmentQuery = new QueryWrapper<>();
        departmentQuery.eq("oid", proposer);
        ZzEmployee zzEmployee = zzEmployeeService.getOne(departmentQuery);
        if (proposer != null) {

            zcAssetmoveapply.setDeptid(zzEmployee.getDeptid());
        } else {
            zcAssetmoveapply.setProposer(myaccount.getAid());
            QueryWrapper<ZzEmployee> departmentQuery2 = new QueryWrapper<>();
            departmentQuery2.eq("oid", myaccount.getAid());
            ZzEmployee zzEmployee2 = zzEmployeeService.getOne(departmentQuery);
            zcAssetmoveapply.setDeptid(zzEmployee2.getDeptid());
        }

        // 设置状态（新增时设置为"W"，修改时不改变原状态）
        if (!isUpdate) {
            zcAssetmoveapply.setStatus("W"); // 初始状态
        }

        // 生成申请单号（仅新增时生成）
        if (!isUpdate && (docNo == null || docNo.isEmpty())) {
            docNo = "YDD" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                    + String.format("%04d", (int)(Math.random() * 10000));
            zcAssetmoveapply.setDocNo(docNo);
            zcAssetmoveapply.setDoctype("YDD");
        }

        // 保存或更新主表信息
        zcAssetmoveapplyService.saveOrUpdate(zcAssetmoveapply);

        // 处理移动明细
        if (assetIds != null && assetIds.length > 0) {
            // 如果是修改，先删除旧的明细
            if (isUpdate) {
                QueryWrapper<ZcAssetmovedetails> deleteWrapper = new QueryWrapper<>();
                deleteWrapper.eq("parentid", oid);
                zcAssetmovedetailsService.remove(deleteWrapper);
            }

            List<ZcAssetmovedetails> details = new ArrayList<>();

            for (int i = 0; i < assetIds.length; i++) {
                if (assetIds[i] == null) {
                    continue; // 跳过空明细
                }

                ZcAssetmovedetails detail = new ZcAssetmovedetails();
                detail.setParentid(zcAssetmoveapply.getOid());
                detail.setAssetId(assetIds[i]);
                detail.setFormPlace(formPlaces != null && i < formPlaces.length ? formPlaces[i] : null);
                detail.setYuanRen(yuanRens != null && i < yuanRens.length ? yuanRens[i] : null);
                detail.setTargetPlace(targetPlaces != null && i < targetPlaces.length ? targetPlaces[i] : null);

                // 处理日期转换
                if (moveDates != null && i < moveDates.length && !moveDates[i].isEmpty()) {
                    try {
                        detail.setMoveDate(LocalDate.parse(moveDates[i]));
                    } catch (DateTimeParseException e) {
                        // 日期格式错误处理
                        detail.setMoveDate(null);
                    }
                }

                detail.setRemark(detailsRemarks != null && i < detailsRemarks.length ? detailsRemarks[i] : null);

                details.add(detail);
            }

            // 保存明细列表
            if (!details.isEmpty()) {
                zcAssetmovedetailsService.saveBatch(details);
            }
        }

        //5.添加审批单子
        LcApproval lcApproval = new LcApproval();
        lcApproval.setDoctype(zcAssetmoveapply.getDoctype());
        lcApproval.setDocNo(zcAssetmoveapply.getDocNo());
        lcApproval.setDocid(zcAssetmoveapply.getOid());
        lcApproval.setProposer(myaccount.getAid());
        lcApproval.setDeptid(zzEmployee.getDeptid());
        lcApproval.setFlowid(zcAssetmoveapply.getFlowid());
        List<NodeVo> lcNodes=lcNodeService.listNode(zcAssetmoveapply.getFlowid());
        lcApproval.setNodeid(lcNodes.get(0).getOid());
        lcApproval.setStatus("O");
        lcApproval.setSubmitDate(LocalDateTime.now());
        lcApprovalService.save(lcApproval);

        return "redirect:/zc-assetmoveapply/tomyzcassetmoveapplylist";
    }

    @RequestMapping("/findZcAssetSimpleInfo")
    @ResponseBody
    public Map<String, Object> findZcAssetSimpleInfo(@RequestParam Long oid) {
        Map<String, Object> result = new HashMap<>();

        // 1. 查询资产基本信息
        ZcAsset asset = zcAssetService.getById(oid);
        if (asset == null) {
            result.put("success", false);
            result.put("message", "资产不存在");
            return result;
        }

        // 2. 查询保管人信息
        ZzEmployee keeperEmp = zzEmployeeService.getById(asset.getKeeper());

        // 3. 查询存放地信息
        JcBasicdatavalue storage = jcBasicdatavalueService.getById(asset.getDepositary());

        // 4. 组装返回数据
        result.put("success", true);
        result.put("keeper", asset.getKeeper()); // 保管人ID
        result.put("depositary", asset.getDepositary()); // 存放地ID

        // 保管人对象
        Map<String, Object> keeperEmpMap = new HashMap<>();
        keeperEmpMap.put("empName", keeperEmp != null ? keeperEmp.getEmpName() : "");
        result.put("keeperEmp", keeperEmpMap);

        // 存放地对象
        Map<String, Object> storageMap = new HashMap<>();
        storageMap.put("name", storage != null ? storage.getName() : "");
        result.put("storage", storageMap);

        return result;
    }

    @RequestMapping("/deleteAssetmoveapply")
    @ResponseBody
    @Transactional
    public boolean deleteAssetmoveapply(@RequestParam Integer oid) {
        try {
            // 1. 先删除所有移动明细（二级关联数据）
            QueryWrapper<ZcAssetmovedetails> detailsQuery = new QueryWrapper<>();
            detailsQuery.eq("parentid", oid);
            zcAssetmovedetailsService.remove(detailsQuery);

            // 2. 删除主表数据
            return zcAssetmoveapplyService.removeById(oid);
        } catch (Exception e) {
            // 事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }

    @RequestMapping("/subAssetmoveapply")
    @ResponseBody
    public boolean subAssetmoveapply(@RequestParam Integer oid){

        QueryWrapper<ZcAssetmovedetails> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parentid",oid);
        long count = zcAssetmovedetailsService.count(queryWrapper);
        if(count > 0){
            QueryWrapper<ZcAssetmoveapply> bxInformalQueryWrapper = new QueryWrapper<>();
            bxInformalQueryWrapper.eq("oid",oid);
            ZcAssetmoveapply zcAssetmoveapply=zcAssetmoveapplyService.getOne(bxInformalQueryWrapper);
            String state="O";
            zcAssetmoveapply.setStatus(state);
            zcAssetmoveapply.setSubmitDate(LocalDateTime.now());
            zcAssetmoveapplyService.updateById(zcAssetmoveapply);
            return true;
        }else {

            return false;

        }

    }


}
